/*
 * Copyright 2005-2013 finalist.cn. All rights reserved.
 * Support: http://www.finalist.cn
 * License: http://www.finalist.cn/license
 */
package com.finalist.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.LockModeType;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.finalist.Filter;
import com.finalist.Page;
import com.finalist.Pageable;
import com.finalist.Setting;
import com.finalist.Setting.StockAllocationTime;
import com.finalist.dao.CouponCodeDao;
import com.finalist.dao.MemberDao;
import com.finalist.dao.MemberRankDao;
import com.finalist.dao.OrderDao;
import com.finalist.dao.OrderItemDao;
import com.finalist.dao.OrderLogDao;
import com.finalist.dao.PaymentDao;
import com.finalist.dao.ProductDao;
import com.finalist.dao.RefundsDao;
import com.finalist.dao.ReturnsDao;
import com.finalist.dao.SnDao;
import com.finalist.entity.Admin;
import com.finalist.entity.Cart;
import com.finalist.entity.Coupon;
import com.finalist.entity.CouponCode;
import com.finalist.entity.Member;
import com.finalist.entity.MemberRank;
import com.finalist.entity.Order;
import com.finalist.entity.Order.OrderStatus;
import com.finalist.entity.Order.PaymentStatus;
import com.finalist.entity.Order.ShippingStatus;
import com.finalist.entity.OrderItem;
import com.finalist.entity.OrderLog;
import com.finalist.entity.OrderLog.Type;
import com.finalist.entity.Payment;
import com.finalist.entity.Product;
import com.finalist.entity.Refunds;
import com.finalist.entity.Returns;
import com.finalist.entity.ReturnsItem;
import com.finalist.entity.Sn;
import com.finalist.service.LogService;
import com.finalist.service.OrderChildrenItemService;
import com.finalist.service.OrderItemService;
import com.finalist.service.OrderService;
import com.finalist.service.StaticService;
import com.finalist.util.SettingUtils;

/**
 * Service - 订单
 * 
 * @author Finalist IT Group
 * @version 3.0
 */
@Service("orderServiceImpl")
public class OrderServiceImpl extends BaseServiceImpl<Order, Long> implements OrderService
{

    private Logger log = Logger.getLogger(OrderServiceImpl.class); 
     
    @Resource(name = "orderDaoImpl")
    private OrderDao orderDao;
    @Resource(name = "orderItemDaoImpl")
    private OrderItemDao orderItemDao;
    @Resource(name = "orderLogDaoImpl")
    private OrderLogDao orderLogDao;
    @Resource(name = "couponCodeDaoImpl")
    private CouponCodeDao couponCodeDao;
    @Resource(name = "snDaoImpl")
    private SnDao snDao;
    @Resource(name = "memberDaoImpl")
    private MemberDao memberDao;
    @Resource(name = "memberRankDaoImpl")
    private MemberRankDao memberRankDao;
    @Resource(name = "productDaoImpl")
    private ProductDao productDao;
    @Resource(name = "paymentDaoImpl")
    private PaymentDao paymentDao;
    @Resource(name = "refundsDaoImpl")
    private RefundsDao refundsDao;
    @Resource(name = "returnsDaoImpl")
    private ReturnsDao returnsDao;
    @Resource(name = "staticServiceImpl")
    private StaticService staticService;
    @Resource(name = "orderChildrenItemServiceImpl")
    private OrderChildrenItemService orderChildrenItemService;
    @Resource(name = "orderItemServiceImpl")
    private OrderItemService orderItemService;
	@Resource(name = "logServiceImpl")
	private LogService logService;
	
    @Resource(name = "orderDaoImpl")
    public void setBaseDao(OrderDao orderDao)
    {
        super.setBaseDao(orderDao);
    }

    @Transactional(readOnly = true)
    public Order findBySn(String sn)
    {
        return orderDao.findBySn(sn);
    }

    @Transactional(readOnly = true)
    public List<Order> findList(Member member, Integer count, List<Filter> filters, List<com.finalist.Order> orders)
    {
        return orderDao.findList(member, count, filters, orders);
    }

    @Transactional(readOnly = true)
    public Page<Order> findPage(Member member, Pageable pageable)
    {
        return orderDao.findPage(member, pageable);
    }

    @Transactional(readOnly = true)
    public Page<Order> findPage(OrderStatus orderStatus, String productName, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired, Long adminId,Pageable pageable)
    {
        return orderDao.findPage(orderStatus, productName, paymentStatus, shippingStatus, hasExpired,adminId, pageable);
    }

    @Transactional(readOnly = true)
    public Page<Order> findPage(Member member, PaymentStatus paymentStatus, Pageable pageable)
    {
        return orderDao.findPage(member, paymentStatus, pageable);
    }

    @Transactional(readOnly = true)
    public Long count(OrderStatus orderStatus, PaymentStatus paymentStatus, ShippingStatus shippingStatus, Boolean hasExpired)
    {
        return orderDao.count(orderStatus, paymentStatus, shippingStatus, hasExpired);
    }

    @Transactional(readOnly = true)
    public Long waitingPaymentCount(Member member)
    {
        return orderDao.waitingPaymentCount(member);
    }

    @Transactional(readOnly = true)
    public Long waitingShippingCount(Member member)
    {
        return orderDao.waitingShippingCount(member);
    }

    @Transactional(readOnly = true)
    public Long allOrderCount(Member member)
    {
        return orderDao.allOrderCount(member);
    }

    @Transactional(readOnly = true)
    public BigDecimal getSalesAmount(Date beginDate, Date endDate)
    {
        return orderDao.getSalesAmount(beginDate, endDate);
    }

    @Transactional(readOnly = true)
    public Integer getSalesVolume(Date beginDate, Date endDate)
    {
        return orderDao.getSalesVolume(beginDate, endDate);
    }


    public void update(Order order, Admin operator)
    {
        Assert.notNull(order);

        Order pOrder = orderDao.find(order.getId());

//        if (pOrder.getIsAllocatedStock())
//        {
            for (OrderItem orderItem : pOrder.getOrderItems())
            {
                if (orderItem != null)
                {
                    Product product = orderItem.getProduct();
                    productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                    if (product != null)
                    {
//                        product.setAllocatedStock(product.getAllocatedStock() - (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                        productDao.merge(product);
                        orderDao.flush();
                        staticService.build(product);
                    }
                }
            }
            for (OrderItem orderItem : order.getOrderItems())
            {
                if (orderItem != null)
                {
                    Product product = orderItem.getProduct();
                    productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                    if (product != null)
                    {
//                        product.setAllocatedStock(product.getAllocatedStock() + (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                        productDao.merge(product);
                        productDao.flush();
                        staticService.build(product);
                    }
                }
            }
//        }

        orderDao.merge(order);

        OrderLog orderLog = new OrderLog();
        orderLog.setType(Type.modify);
        orderLog.setOperator(operator != null ? operator.getUsername() : null);
        orderLog.setOrder(order);
        orderLogDao.persist(orderLog);
    }

    public void confirm(Order order, Admin operator)
    {
        Assert.notNull(order);

        order.setOrderStatus(OrderStatus.confirmed);
        orderDao.merge(order);

        OrderLog orderLog = new OrderLog();
        orderLog.setType(Type.confirm);
        orderLog.setOperator(operator != null ? operator.getUsername() : null);
        orderLog.setOrder(order);
        orderLogDao.persist(orderLog);
    }

    public void complete(Order order, Admin operator)
    {
        Assert.notNull(order);

        Member member = order.getMember();
        memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE);

        if (order.getShippingStatus() == ShippingStatus.partialShipment || order.getShippingStatus() == ShippingStatus.shipped)
        {
            member.setPoint(member.getPoint() + order.getPoint());
            for (Coupon coupon : order.getCoupons())
            {
                couponCodeDao.build(coupon, member);
            }
        }

        if (order.getShippingStatus() == ShippingStatus.unshipped || order.getShippingStatus() == ShippingStatus.returned)
        {
            CouponCode couponCode = order.getCouponCode();
            if (couponCode != null)
            {
                couponCode.setIsUsed(false);
                couponCode.setUsedDate(null);
                couponCodeDao.merge(couponCode);

                order.setCouponCode(null);
                orderDao.merge(order);
            }
        }

        member.setAmount(member.getAmount().add(order.getAmountPaid()));
        if (!member.getMemberRank().getIsSpecial())
        {
            MemberRank memberRank = memberRankDao.findByAmount(member.getAmount());
            if (memberRank != null && memberRank.getAmount().compareTo(member.getMemberRank().getAmount()) > 0)
            {
                member.setMemberRank(memberRank);
            }
        }
        memberDao.merge(member);

        if (order.getIsAllocatedStock())
        {
            for (OrderItem orderItem : order.getOrderItems())
            {
                if (orderItem != null)
                {
                    Product product = orderItem.getProduct();
                    productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                    if (product != null && product.getStock() != null)
                    {
                        product.setAllocatedStock(product.getAllocatedStock() - (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                        productDao.merge(product);
                        orderDao.flush();
                        staticService.build(product);
                    }
                }
            }
            order.setIsAllocatedStock(false);
        }

        for (OrderItem orderItem : order.getOrderItems())
        {
            if (orderItem != null)
            {
                Product product = orderItem.getProduct();
                productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                if (product != null)
                {
                    Integer quantity = orderItem.getQuantity();
                    Calendar nowCalendar = Calendar.getInstance();
                    Calendar weekSalesCalendar = DateUtils.toCalendar(product.getWeekSalesDate());
                    Calendar monthSalesCalendar = DateUtils.toCalendar(product.getMonthSalesDate());
                    if (nowCalendar.get(Calendar.YEAR) != weekSalesCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.WEEK_OF_YEAR) > weekSalesCalendar.get(Calendar.WEEK_OF_YEAR))
                    {
                        product.setWeekSales((long) quantity);
                    }
                    else
                    {
                        product.setWeekSales(product.getWeekSales() + quantity);
                    }
                    if (nowCalendar.get(Calendar.YEAR) != monthSalesCalendar.get(Calendar.YEAR) || nowCalendar.get(Calendar.MONTH) > monthSalesCalendar.get(Calendar.MONTH))
                    {
                        product.setMonthSales((long) quantity);
                    }
                    else
                    {
                        product.setMonthSales(product.getMonthSales() + quantity);
                    }
                    product.setSales(product.getSales() + quantity);
                    product.setWeekSalesDate(new Date());
                    product.setMonthSalesDate(new Date());
                    productDao.merge(product);
                    orderDao.flush();
                    staticService.build(product);
                }
            }
        }

        order.setOrderStatus(OrderStatus.completed);
        order.setExpire(null);
        orderDao.merge(order);

        OrderLog orderLog = new OrderLog();
        orderLog.setType(Type.complete);
        orderLog.setOperator(operator != null ? operator.getUsername() : null);
        orderLog.setOrder(order);
        orderLogDao.persist(orderLog);
    }

    public void cancel(Order order, Admin operator)
    {
        Assert.notNull(order);

        CouponCode couponCode = order.getCouponCode();
        if (couponCode != null)
        {
            couponCode.setIsUsed(false);
            couponCode.setUsedDate(null);
            couponCodeDao.merge(couponCode);

            order.setCouponCode(null);
            orderDao.merge(order);
        }

        if (order.getIsAllocatedStock())
        {
            for (OrderItem orderItem : order.getOrderItems())
            {
                if (orderItem != null)
                {
                    Product product = orderItem.getProduct();
                    productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                    if (product != null && product.getStock() != null)
                    {
                        product.setAllocatedStock(product.getAllocatedStock() - (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                        productDao.merge(product);
                        orderDao.flush();
                        staticService.build(product);
                    }
                }
            }
            order.setIsAllocatedStock(false);
        }

        order.setOrderStatus(OrderStatus.cancelled);
        order.setExpire(null);
        orderDao.merge(order);
//        /**
//         * 查询是否购买号码
//         */
//        //查询订单表中字段
//        String selectedPhone = order.getSelectedPhone();
//        if(selectedPhone!=null){
//        	//更新号码状态
//        	NeusoftPhoneNumber neuphone = neusoftPhoneNumberService.getByServiceId(selectedPhone);
//        	neuphone.setStatus(Status.lock);
//        	neusoftPhoneNumberService.update(neuphone);
////        	neusoftPhoneNumberService.unlockPhoneNum(phoneNums);
//        }
//        
//        //查询订单关联手机表中数据
//        List<NeusoftPhoneNumber> neulist =  order.getNeusoftPhoneNumbers();
//        if(neulist!=null&&neulist.size()>0){
//        	for(NeusoftPhoneNumber neu:neulist){
//        		//更新号码状态
//        		neu.setStatus(Status.lock);
//            	neusoftPhoneNumberService.update(neu);
//        	}
//        }
        /**
         * 
         */
        OrderLog orderLog = new OrderLog();
        orderLog.setType(Type.cancel);
        orderLog.setOperator(operator != null ? operator.getUsername() : null);
        orderLog.setOrder(order);
        orderLogDao.persist(orderLog);
    }

    public void payment(Order order, Payment payment, Admin operator)
    {
        Assert.notNull(order);
        Assert.notNull(payment);

        orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

        payment.setOrder(order);
        paymentDao.merge(payment);
        if (payment.getMethod() == Payment.Method.deposit)
        {
            Member member = order.getMember();
            memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE);
            member.setBalance(member.getBalance().subtract(payment.getAmount()));
            memberDao.merge(member);

        }

        Setting setting = SettingUtils.get();
        if (!order.getIsAllocatedStock() && setting.getStockAllocationTime() == StockAllocationTime.payment)
        {
            for (OrderItem orderItem : order.getOrderItems())
            {
                if (orderItem != null)
                {
                    Product product = orderItem.getProduct();
                    productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                    if (product != null && product.getStock() != null)
                    {
                        product.setAllocatedStock(product.getAllocatedStock() + (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                        productDao.merge(product);
                        log.info("orderDao更新");
                        orderDao.flush();
                        staticService.build(product);
                    }
                }
            }
            order.setIsAllocatedStock(true);
        }

        
        
        
//        boolean isMiao = false;//云健康服务需要发送信息到妙健康
//        boolean isBoss = false;
//        List<OpenMiaoService> los = new ArrayList<OpenMiaoService>();
//        
//        /**
//         * 开通云3服务
//         */
//        for (OrderItem orderItem : order.getOrderItems())
//        {
//            if (orderItem != null)
//            {
//                Product product = orderItem.getProduct();
//                try {
//					//确定购买商贸为云健康服务
//					if(product != null){
//						if(product.getCombinationType()!=null)
//						if(product.getCombinationType().equals(CombinationType.yun_healthy_service)){//云健康
//							OpenMiaoService os = new OpenMiaoService();
//							/**
//							 * 乐语用户调用妙健康接口
//							 * 非乐语用户调用boss接口
//							 */
//							String oldPhone = order.getCloundServicesPhone();//老用户手机号
//					    	if(oldPhone!=null&&!oldPhone.equals("")){//老用户给妙关爱
//					    		isMiao =true;
//					    		os.setErpPhone(oldPhone);
//					    		String hid = product.getHealthErpId();
//					    		os.setErpProductId(hid);//妙健康测试ID
//					    	}else{
//					    		isBoss = true;
//					    		os.setErpPhone(order.getSelectedPhone());
//					    		os.setErpProductId(product.getExternalId());//bosss测试ID
//					    		NeusoftPhoneNumber nphone = neusoftPhoneNumberService.getByServiceId(order.getSelectedPhone());
//					    		if(nphone!=null){
//					    			os.setErpPhoneCode(nphone.getCityCode());
//					    		}
//					    	}
//					    	os.setErpPrice(product.getPrice()!=null?product.getPrice().toString():"0");
//					    	los.add(os);
//						}else if(product.getCombinationType().equals(CombinationType.miao_care)){//妙关爱
//							Set<PackageProduct> pset = product.getPackageProducts();//取妙表中数据
//							
//							if(pset!=null&&!pset.isEmpty()){
//								Iterator<PackageProduct> it = pset.iterator();
//								while(it.hasNext()){
//									PackageProduct pro =  it.next();
//									if(pro!=null){
//										if(pro.getProducts()!=null&&pro.getProducts().getCombinationType()!=null)
//										if(pro.getProducts().getCombinationType().equals(CombinationType.pack_service)){//妙关爱套包中包含的云3服务
//											isBoss = true;
//											List<NeusoftPhoneNumber> nfplist = order.getNeusoftPhoneNumbers();
//											if(nfplist!=null&&nfplist.size()>0){
//												for(NeusoftPhoneNumber np:nfplist){
//													OpenMiaoService os = new OpenMiaoService();
////                								os.setErpProductId(pro.get);
//													os.setErpProductId(pro.getProduct().getExternalId());//bosss测试ID
//													os.setErpPhone(np.getServiceId());
//													os.setErpPhoneCode(np.getCityCode());
//													os.setOfferType(1);
//													os.setEffectType(0);
//													los.add(os);
//												}
//											}
//										}
//									}
//								}
//							}
//						}
//						
//					}
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//					log.error("选择开通云3服务接口异常："+e.toString());
//				}
//            }
//        }        
//        
//        
        
        
        
        order.setAmountPaid(order.getAmountPaid().add(payment.getAmount()));
        order.setFee(payment.getFee());
        order.setExpire(null);
        if (order.getAmountPaid().compareTo(order.getAmount()) >= 0)
        {
            order.setOrderStatus(OrderStatus.confirmed);
            order.setPaymentStatus(PaymentStatus.paid);
//            log.info("更新订单状态");
//            try {
//                //订单支付成功后发送订单信息给妙健康
//                if(isMiao&&los.size()>0){
//                	for(OpenMiaoService ose:los){
//                		/**
//                		 * 调用妙健康接口
//                		 */
//                		this.syncMiaoHealthy(ose);
//                	}
//                }
//                if(isBoss&&los.size()>0){
//	            	for(OpenMiaoService ose:los){
//	                	/**
//	                	 * 调用boss接口
//	                	 */
//	            		this.syncBossService(ose);
//	            	}
//                }
//			} catch (Exception e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//				log.error("掉用开通云3服务接口异常："+e.toString());
//			}
            
        }
        else if (order.getAmountPaid().compareTo(new BigDecimal(0)) > 0)
        {
            order.setOrderStatus(OrderStatus.confirmed);
            order.setPaymentStatus(PaymentStatus.partialPayment);
        }
//        orderDao.merge(order);
        orderDao.flush();
//        log.info("订单状态:"+order.getOrderStatus());
//        log.info("订单支付状态:"+order.getPaymentStatus());
        log.info("刷新订单状态完毕");
        OrderLog orderLog = new OrderLog();
        orderLog.setType(Type.payment);
        orderLog.setOperator(operator != null ? operator.getUsername() : null);
        orderLog.setOrder(order);
        orderLogDao.persist(orderLog);
        log.info("记录订单日志完毕");

    }

    public void refunds(Order order, Refunds refunds, Admin operator)
    {
        Assert.notNull(order);
        Assert.notNull(refunds);

        orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

        refunds.setOrder(order);
        refundsDao.persist(refunds);
        if (refunds.getMethod() == Refunds.Method.deposit)
        {
            Member member = order.getMember();
            memberDao.lock(member, LockModeType.PESSIMISTIC_WRITE);
            member.setBalance(member.getBalance().add(refunds.getAmount()));
            memberDao.merge(member);

        }

        order.setAmountPaid(order.getAmountPaid().subtract(refunds.getAmount()));
        order.setExpire(null);
        if (order.getAmountPaid().compareTo(new BigDecimal(0)) == 0)
        {
            order.setPaymentStatus(PaymentStatus.refunded);
        }
        else if (order.getAmountPaid().compareTo(new BigDecimal(0)) > 0)
        {
            order.setPaymentStatus(PaymentStatus.partialRefunds);
        }
        orderDao.merge(order);

        OrderLog orderLog = new OrderLog();
        orderLog.setType(Type.refunds);
        orderLog.setOperator(operator != null ? operator.getUsername() : null);
        orderLog.setOrder(order);
        orderLogDao.persist(orderLog);
    }


    public void returns(Order order, Returns returns, Admin operator)
    {
        Assert.notNull(order);
        Assert.notNull(returns);
        Assert.notEmpty(returns.getReturnsItems());

        orderDao.lock(order, LockModeType.PESSIMISTIC_WRITE);

        returns.setOrder(order);
        returnsDao.persist(returns);
        for (ReturnsItem returnsItem : returns.getReturnsItems())
        {
            OrderItem orderItem = order.getOrderItem(returnsItem.getSn());
            if (orderItem != null)
            {
                orderItemDao.lock(orderItem, LockModeType.PESSIMISTIC_WRITE);
                orderItem.setReturnQuantity(orderItem.getReturnQuantity() + returnsItem.getQuantity());
            }
        }
        if (order.getReturnQuantity() >= order.getShippedQuantity())
        {
            order.setShippingStatus(ShippingStatus.returned);
        }
        else if (order.getReturnQuantity() > 0)
        {
            order.setShippingStatus(ShippingStatus.partialReturns);
        }
        order.setExpire(null);
        orderDao.merge(order);

        OrderLog orderLog = new OrderLog();
        orderLog.setType(Type.returns);
        orderLog.setOperator(operator != null ? operator.getUsername() : null);
        orderLog.setOrder(order);
        orderLogDao.persist(orderLog);
    }

    @Override
    public void delete(Order order)
    {
        /*if (order.getIsAllocatedStock())
        {*/
            for (OrderItem orderItem : order.getOrderItems())
            {
                if (orderItem != null)
                {
                    Product product = orderItem.getProduct();
                    productDao.lock(product, LockModeType.PESSIMISTIC_WRITE);
                    if (product != null && product.getStock() != null)
                    {
                        product.setAllocatedStock(product.getAllocatedStock() - (orderItem.getQuantity() - orderItem.getShippedQuantity()));
                        productDao.merge(product);
                        orderDao.flush();
                        staticService.build(product);
                    }
                }
            }
        /*}*/
        super.delete(order);
    }

    @Override
    public Page<Order> findPageBywaitingPayment(Member member, Pageable pageable)
    {
        return orderDao.findPageBywaitingPayment(member, pageable);
    }

    @Override
    public Page<Order> findPage(Member member, Integer statue, Pageable pageable)
    {
        return orderDao.findPageByStatue(member, statue, pageable);
    }

    @Override
    public Page<Order> findPageBywaitingShipping(Member member, Pageable pageable)
    {
        return orderDao.findPageBywaitingShipping(member, pageable);
    }

    @Override
    public List<Order> findByPaymentStatus(PaymentStatus paymentStatus, boolean isSelectedPhone)
    {
        return orderDao.findByPaymentStatus(paymentStatus, isSelectedPhone);
    }

    @Override
    public Page<Order> findPageByOrderSn(Member member, String contentStr, Pageable pageable)
    {
        return orderDao.findPageByOrderSn(member, contentStr, pageable);
    }

    @Override
    public Page<Order> findPageByKeyWord(Member member, String keyWord, Pageable pageable)
    {
        List<Order> orderList = orderItemDao.getOrderListByKeyWord(keyWord);
        List<String> orderSnList = new ArrayList<String>();
        orderSnList.add(keyWord);
        if (CollectionUtils.isNotEmpty(orderList))
        {
            for (Order order : orderList)
            {
                orderSnList.add(order.getSn());
            }
        }
        return orderDao.findPageByOrderSnList(member, orderSnList, pageable);
    }

    @Override
    public BigDecimal getTotalConsumeMoney(Member member)
    {
        return orderDao.getTotalConsume(member);
    }

    @Override
    public Long waitingReceiveOrderCount(Member member)
    {
        return orderDao.waitingReceiveOrderCount(member);
    }

    @Override
    public Long finishOrderCount(Member member)
    {
        return orderDao.finishOrderCount(member);
    }

    @Override
    public Long cancelOrderCount(Member member)
    {
        return orderDao.cancelOrderCount(member);
    }

    @Override
    public void merge(Order order)
    {
        orderDao.merge(order);
    }
    

	@Override
	public Long expiredOrderCount(Member member) {
		
		return orderDao.expiredOrderCount(member);
	}

	public Order create(Cart cart) {
	   Assert.notNull(cart);
       Assert.notNull(cart.getMember());
       Assert.notEmpty(cart.getCartItems());

       Order order = new Order();
       order.setSn(snDao.generate(Sn.Type.order));
       order.setOrderStatus(OrderStatus.unconfirmed);
       order.setPaymentStatus(PaymentStatus.unpaid);
       order.setFee(new BigDecimal(0));
       order.setPromotionDiscount(cart.getDiscount());
       order.setCouponDiscount(new BigDecimal(0));
       order.setOffsetAmount(new BigDecimal(0));
       order.setPoint(cart.getEffectivePoint());
       //order.setMember(cart.getMember());
       
       orderDao.persist(order);
       return order;
	}

	@Override
	public List<Order>  findPage(Member member, Integer status) {
		return orderDao.findPage(member, status);
	}

	@Override
	public void updateOrderNopaid() {
		orderDao.updateOrderNopaid();
	}

}